/**
 * @name LanguageChange
 * @description 语言切换
 * @description 此处的语言切换，是手动替换，而非自动翻译后替换，保证了语言切换后的准确性
 */
import React, { Component } from "react";
import { Title } from "@/component";
import intl from "react-intl-universal";
import { Select } from "antd";

import styles from "./styles.module.less";

const SUPPOER_LOCALES = [
  {
    name: "English",
    value: "en-US"
  },
  {
    name: "简体中文",
    value: "zh-CN"
  },
  {
    name: "繁體中文",
    value: "zh-TW"
  }
];
class LanguageChange extends Component {
  state = {
    loading: false,
    lang: ""
  };
  componentDidMount() {
    this.getJson();
  }
  /**
   * @name onChange
   * @param {String} 刷新页面
   * @description 切换语言
   */
  onChange = (val) => {
    window.location.search = `?lang=${val}`;
  };

  /**
   * @name getJson
   * @param {String} value
   * @description 切换语言
   */
  getJson = () => {
    let lang = "zh-CN"; //默认简体中文
    const search = window.location.search;

    if (search) {
      lang = search.split("?lang=")[1];
    }

    if (SUPPOER_LOCALES.filter((v) => v.value === lang).length === 0) {
      lang = "zh-CN";
    }

    const data = require(`./locales/${lang}.json`);
    intl
      .init({
        currentLocale: lang,
        locales: {
          [lang]: data
        }
      })
      .then(() => {
        this.setState({ lang });
      });
  };

  render() {
    let price = 123456.123;
    let start = new Date();
    let end = new Date();
    let expires = new Date();
    let message = "class LanguageChange extends Component";
    return (
      <div>
        <div className={styles.block}>
          <h3>此处的语言切换，是手动替换，而非自动翻译后替换，保证了语言切换后的准确性;若需整页面翻译可以使用百度翻译api</h3>
          <Select style={{ width: 200 }} value={this.state.lang} onChange={(value) => this.onChange(value)}>
            {SUPPOER_LOCALES.map((item) => (
              <Select.Option key={item.value} value={item.value} label={item.name}>
                {item.name}
              </Select.Option>
            ))}
          </Select>
        </div>
        <div className={styles.block}>
          <Title text={"Basic Examples:"} />
          <div>{intl.get("SIMPLE")}</div>
          <div>{intl.get("HELLO", { name: "Tony", where: "Alibaba" })}</div>
        </div>

        <div className={styles.block}>
          <Title text={"Currency Example:"} />
          <div>{intl.get("SALE_PRICE", { price })}</div>
        </div>

        <div className={styles.block}>
          <Title text={"Date Examples:"} />
          <div>{intl.get("SALE_START", { start })}</div>
          <div>{intl.get("SALE_END", { end })}</div>
          <div>{intl.get("COUPON", { expires })}</div>
        </div>

        <div className={styles.block}>
          <Title text={"HTML Examples:"} />
          <div dangerouslySetInnerHTML={{ __html: intl.get("TIP") }} />
          <div dangerouslySetInnerHTML={{ __html: intl.get("TIP_VAR", { message }) }} />
        </div>
      </div>
    );
  }
}
export default LanguageChange;
